#!/bin/sh

PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH

# Authentication Credentials Installer postflight shell script.  
# Copyright 2002-2012, Bombich Software, Inc.

print_result() {
	if [ $? == 0 ]; then
		printf "Succeeded\n" >> "$LOG"
	else
		printf "Failed\n" >> "$LOG"
	fi
}

pkg_res="$1/Contents/Resources"
pkg_pubkey="$pkg_res/ccc_dsa.pub"
pkg_privkey="$pkg_res/ccc_dsa"

root_ssh="/var/root/.ssh"
t_pubkey="$root_ssh/ccc_dsa.pub"
t_privkey="$root_ssh/ccc_dsa"

LOG="/Library/Logs/CCC.log"

sourceHW="%MACADDRESS%"

# Remove the empty /tmp/ccc file that exists only so the payload-free package will install without error
rm /tmp/ccc 2> /dev/null

myHW=`/usr/sbin/ioreg -c IOPlatformExpertDevice | /usr/bin/awk -F\" '/IOPlatformSerialNumber/ { print $4 }'`

printf "============= Authentication Credentials Installer: `date` =============\n\n" >> "$LOG"
printf "Running Authentication Credentials Installer package postflight script\n\n" >> "$LOG"
printf "hostname: `hostname`\n\n" >> "$LOG"

# Key setup
if [ "$myHW" = "$sourceHW" ]; then
	printf "`date '+%H:%M:%S'`    [Installing the public and private DSA key pairs on the local machine]\n" >> "$LOG"
	# We're installing the public and private DSA key pairs on the source machine
	
	if [ ! -d "$root_ssh" ]; then
		printf "`date '+%H:%M:%S'`    Creating directory: /var/root/.ssh... " >> "$LOG"
		mkdir "$root_ssh"
		print_result
	fi
	
	if [ -f "$t_privkey" -a -f "$t_pubkey" ]; then
		# copy the existing public key into the installer package, we're going to use the existing key
		printf "`date '+%H:%M:%S'`    CCC-specific key pair for root user present, copying existing public key to package... " >> "$LOG"
		cp "$t_pubkey" "$pkg_pubkey"
		print_result
	else
		# Install the pub and private keys
		printf "`date '+%H:%M:%S'`    Installing CCC-specific key pair into root account... " >> "$LOG"
		cp "$pkg_privkey" "$t_privkey"
		cp "$pkg_pubkey" "$t_pubkey"
		print_result
	fi

	# Fix any permissions problems
	chown root:wheel -R "$root_ssh"
	chmod 500 "$root_ssh"
	chmod 400 "$t_privkey" "$t_pubkey"
	chmod 644 "$t_auth"
	
	printf "`date '+%H:%M:%S'`    Securely removing private key from package... " >> "$LOG"
	srm "$pkg_privkey"
	print_result

else
	error=0
	new_host=`awk '{print $NF}' "$pkg_pubkey"`
	# We're installing the public key into root's authorized_keys file on a destination
	printf "`date '+%H:%M:%S'`    [Authorizing $new_host to authenticate to this machine]\n" >> "$LOG"
	
	# Pre-flight sanity checking of the destination machine's configuration
	# Is Remote Login enabled?
	printf "`date '+%H:%M:%S'`    Checking that the Remote Login service is turned on...\n" >> "$LOG"
	remoteLoginEnabled=`launchctl list | grep ssh | wc -l | cut -c 8`
	if [ $remoteLoginEnabled -gt 0 ]; then
		printf "`date '+%H:%M:%S'`    The Remote Login service is enabled\n" >> "$LOG"
	else
		error="The Remote Login service is not enabled. Please turn on this service in the Sharing Preference Pane."
		printf "`date '+%H:%M:%S'`    ERROR: $error\n" >> "$LOG"
	fi
	
	# Is the root user permitted to use the Remote Login service?
	printf "`date '+%H:%M:%S'`    Verifying System Administrator access to the Remote Login service...\n" >> "$LOG"
	isMember=`dsmemberutil checkmembership -U root -G com.apple.access_ssh`
	if [ "$?" != "0" ]; then
		printf "`date '+%H:%M:%S'`    There is not a service access control list for the ssh service\n" >> "$LOG"
	elif [ "$isMember" = "user is a member of the group" ]; then
		printf "`date '+%H:%M:%S'`    The System Administrator belongs to the com.apple.access_ssh group\n" >> "$LOG"
	else
		error="The System Administrator does not have access to the Remote Login service."
		printf "`date '+%H:%M:%S'`    ERROR: $error\n" >> "$LOG"
	fi
	
	# Is the root user errantly disabled?
	aa=`dscl . read /Users/root AuthenticationAuthority | grep "DisabledUser" | wc -l | cut -c 8`
	if [ "$aa" = "1" ]; then
		# The proper way to disable the root account is to remove the AuthenticationAuthority attribute from its account
		echo "Properly disabling the root account"
		dscl . delete /Users/root AuthenticationAuthority
	fi


	# Dump any customizations from /etc/sshd_config
	printf "`date '+%H:%M:%S'`    /etc/sshd_config customizations:\n" >> "$LOG"
	grep -v -e "^#" -e "^$" /etc/sshd_config >> "$LOG"
	printf "\n" >> "$LOG"
	
	
	if [ -f "$pkg_privkey" ]; then
		# The user didn't install the package on the source first!
		printf "`date '+%H:%M:%S'`    Private key exists in package, package must be installed on local machine first!\n\n" >> "$LOG"
		printf "================================================================================\n\n\n" >> "$LOG"
		exit 2
	fi

	s_wrapper="$pkg_res/rsync-wrapper.sh"
	t_wrapper="$root_ssh/rsync-wrapper.sh"
	t_auth="$root_ssh/authorized_keys"

	if [ ! -d "$root_ssh" ]; then
		printf "`date '+%H:%M:%S'`    Creating directory: /var/root/.ssh... " >> "$LOG"
		mkdir "$root_ssh"
		print_result
	fi
	
	# Copy the wrapper script and restrict its permissions
	printf "`date '+%H:%M:%S'`    Copying rsync wrapper script to /var/root/.ssh/ ... " >> "$LOG"
	cp "$s_wrapper" "$t_wrapper"
	chmod 500 "$t_wrapper"
	print_result

	if [ -f "$pkg_pubkey" ]; then
		# Remove any previous instances of the source host's key
		new_host=`awk '{print $NF}' "$pkg_pubkey"`
		printf "`date '+%H:%M:%S'`    Removing existing authorizations for source machine \"$new_host\" from root authorization file... " >> "$LOG"
		perl -n -i -e "print unless /$new_host/" "$t_auth"
		print_result

		# Tack on the key and the rsync-wrapper
		printf "`date '+%H:%M:%S'`    Enabling public key authentication for source machine's root account... " >> "$LOG"
		new_key=`cat "$pkg_pubkey"`
		echo "command=\"$t_wrapper\" $new_key" >> "$t_auth"
		print_result
		
		# Fix any permissions problems
		chown root:wheel -R "$root_ssh"
		chmod 500 "$root_ssh"
		chmod 644 "$t_auth"
	fi
	
	if [ "$error" != "0" ]; then
		if [ "$COMMAND_LINE_INSTALL" = "" ]; then
			osascript -e "tell application \"SystemUIServer\"" -e "activate" -e "display dialog \"The installation succeeded, but the Remote Login service is not properly configured: \n\n$error \n\nPlease refer to the \\\"Using Carbon Copy Cloner to backup to another Macintosh on your network\\\" section of the CCC documentation for assistance.\"" -e "end tell"
			open "http://help.bombich.com/kb/dmg-and-remote/using-carbon-copy-cloner-to-backup-to-another-macintosh-on-your-network#enable-remote-login"
		else
			printf "The installation succeeded, but the Remote Login service is not properly configured:\n\n$error\n\nPlease refer to the \"Using Carbon Copy Cloner to backup to another Macintosh on your network\" section of the CCC documentation for assistance.\n" > `tty`
		fi
	fi
fi

printf "`date '+%H:%M:%S'`    Postflight script has completed.\n\n" >> "$LOG"
printf "================================================================================\n\n\n" >> "$LOG"
